import { AnimationClip, animation, Sprite, SpriteFrame } from 'cc';
import ResourceManager from '../Runtime/ResourceManager';
import { StateMachine } from './StateMachine';

export class State {
    private animationClip: AnimationClip;

    constructor(
        private pms: StateMachine,
        private path: string,
        private wrapNode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
        speed: number = 1 / 8,
        events: AnimationClip.IEvent[] = [],
    ) {
        this.init(speed, events);
    }

    async init(speed: number, events: AnimationClip.IEvent[]) {
        const reg = /\((\d+)\)/;

        const promise = ResourceManager.Instance.loadDir(this.path);
        this.pms.waitingList.push(promise);
        const spriteFrames = await promise;
        spriteFrames.sort((a, b) => {
            const aIndex = parseInt(a.name.match(reg)[1], 10);
            const bIndex = parseInt(b.name.match(reg)[1], 10);
            return aIndex - bIndex;
        });

        this.animationClip = new AnimationClip();
        this.animationClip.duration = 1.0;

        const track = new animation.ObjectTrack();
        track.path = new animation.TrackPath()
            .toComponent(Sprite)
            .toProperty("spriteFrame");
        const frames: Array<[number, SpriteFrame]> = spriteFrames.map(
            (item, index) => [speed * index, item]
        );
        // TODO 这里加载的frames多了一帧。。
        track.channel.curve.assignSorted(frames);
        this.animationClip.name = this.path;
        this.animationClip.addTrack(track);
        this.animationClip.duration = frames.length * speed;
        this.animationClip.wrapMode = this.wrapNode;

        this.animationClip.events = events;
    }

    run() {
        if (this.pms.animationComponent?.defaultClip?.name === this.animationClip?.name) {
            return;
        }

        this.pms.animationComponent.defaultClip = this.animationClip;
        this.pms.animationComponent.play();
    }
}

